package com.neusoft.springdemo.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * @author chens
 *
 */
public class LoginInterceptor implements HandlerInterceptor {
	private Logger logger = Logger.getLogger(LoginInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String userName = (String) request.getSession().getAttribute("login_user");

		logger.info("preHandle================" + userName);
		String uri = request.getRequestURI();

		// 登录页面和静态资源不能拦截

		if (userName != null || uri.endsWith("login.do") || uri.endsWith(".html") || uri.contains("/images/")
				|| uri.contains("/css/") || uri.contains("/js/") || uri.contains("/upload/")) {

			/* if (userName != null || uri.endsWith(".html")) { */
			// 返回true表示不拦截
			return true;
		}
		response.sendRedirect(request.getContextPath()+"/login.html");
		// 返回false表示会被拦截
		return false;

	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		logger.info("postHandle================");

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

		logger.info("afterCompletion================");
	}

}
